package com.neusoft.neuiotms.dcom.converter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.HolidayDTO;
import com.neusoft.neuiotms.dcom.model.Holiday;
import com.neusoft.neuiotms.dcom.repository.HolidayRepository;
import com.neusoft.neuiotms.dcom.vo.HolidayVO;

@Component
public class HolidayConverter extends AbstractConverter<Holiday, HolidayDTO> {

    @Autowired
    private HolidayRepository holidayRepository;

    @Override
    public Holiday toModel(final HolidayDTO dto) {

        Holiday model;

        if (dto.isNew()) {
            model = new Holiday();
        } else {
            model = this.holidayRepository.getOne(dto.getId());
        }

        model.setDate(dto.getDate());
        model.setName(dto.getName());
        model.setType(dto.getType());

        return model;
    }

    @Override
    public HolidayDTO toDTO(final Holiday model, final boolean forListView) {

        final HolidayDTO dto = new HolidayDTO();

        dto.setId(model.getId());
        dto.setDate(model.getDate());
        dto.setName(model.getName());
        dto.setType(model.getType());

        return dto;
    }

    public Holiday toModel(final HolidayVO vo) {

        final Holiday model = new Holiday();

        model.setDate(vo.getDate());
        model.setName(vo.getName());

        if (StringUtils.isNotBlank(vo.getType())) {
            final String[] splitData = vo.getType().split("_");
            if (splitData.length == 2) {
                model.setType(splitData[1]);
            }
        }

        return model;
    }
}
